import React,{
  useEffect,useState
} from 'react'

import {
  useDispatch,useSelector
} from 'react-redux'

import * as api from '../../../api/index'

import { Space, Table,Button, Spin,Input,Modal,Badge,Select } from 'antd';


import My_modal from '../../../compontents/My_modal';//子组件
import Popconfirms from '../../../compontents/Popconfirm';

import { debounce }  from 'lodash'

const { Option } = Select;



function OrderList() {
  const dispatch = useDispatch()

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [val,setVal] = useState('')

  const [modal_type,setModal] =  useState('')

  const [select_data,setSelect_data] = useState([])

  useEffect(() => {
    dispatch(api.get_list())
  },[dispatch])

  let data = useSelector((state) => {
      return state.reduce.data
  })

  let load = useSelector((state) => {
    return state.reduce.loading
  })

  const columns = [
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <a>{text}</a>,
    },
    {
      title: 'age',
      dataIndex: 'age',
      defaultSortOrder: 'descend',
      sorter: (a, b) => a.age - b.age,
      key: 'age',
    },
    {
      title: 'Image',
      dataIndex: 'img',
      key: 'img',
      render: (img) => <img src={img} />,
    },
    {
      title: 'City',
      dataIndex: 'city',
      key: 'city',
    },
    {
      title: 'Type',
      dataIndex: 'type',
      key: 'type',
      render: (_, record) => (
        <Space size="middle">
          <Badge status={set_state(record.type)} />
          <span>{record.type}</span>
        </Space>
      )
    },
   
    {
      title: 'Action',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button onClick={() => onEdit(record)}>编辑</Button>

          <Popconfirms title='删除' record={record} fn={() => onDelete(record)}></Popconfirms>
          {/* <Button 
            onClick={debounce(() => onDelete(record),3000)}>
            Delete
          </Button> */}
        </Space>
      ),
    },
  ];

  const set_state = (record) => {
    switch (record) {
      case '正常营业':
        return 'success'
        
      case '门店关闭':
        return 'error'

      case '暂停营业':
          return 'processing'
      default:
        break;
    }
  }

  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      setSelect_data(selectedRows)
    },
    getCheckboxProps: (record) => ({
      disabled: record.name === 'Disabled User',
      // Column configuration not to be checked
      name: record.name,
    }),
  };


  const onDelete = (record) => {//删除

    dispatch(api.del_item(record))
  }

  const onAdd = () => { //添加
    setIsModalVisible(true);
    setModal('')
  }

  const onEdit = (record) => { //回显

    setIsModalVisible(true);

    setModal(record)

  }

  const handleChange = (value) => {//下拉筛选
  
    dispatch(api.filter_data(value))
  };

  const onEnter = () => {
    dispatch(api.filter_data(val))
  }

  const handleOk = (values) => {  //编辑
    setIsModalVisible(false);

    if(values.id) {
      console.log(values);
       dispatch(api.edit_data(values))
       
    }
    else {
      let obj = {
        name : values.name,
        id : new Date() * 1,
        key : data.length + 1,
        age : values.age,
        type : values.type,
        img : 'http://dummyimage.com/100x100/f29779',
        city : values.city
      }
  
      dispatch(api.set_data(obj))
    }
  };

  const all_del = () => { //批量删除
      dispatch(api.all_Deleit(select_data))
  }

  const handleCancel = () => { 
    setIsModalVisible(false);
  
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  let my_form = {
    onFinishFailed,handleCancel,handleOk,modal_type,data
  }

  return (
    <div>
      <div className="head" style={{display:'flex'}}>
          <Input  onChange={(e) => setVal(e.target.value)} 
          onPressEnter={onEnter}
          style={{width:'20vw'}}></Input>
          <Button onClick={onEnter}>搜索</Button>

          <Select defaultValue=""  
            style={{ width: 120 }} onChange={handleChange}>
              <Option value="正常营业">正常营业</Option>
              <Option value="门店关闭">门店关闭</Option>
              <Option value="暂停营业">暂停营业</Option>
            </Select>
          <Button onClick={onAdd}>添加</Button>
          {
              select_data.length > 1 && <Popconfirms title={'批量删除'} 
              fn={() => all_del(select_data)}></Popconfirms>
              //  <Button onClick={all_del}>批量删除</Button>
          }
      </div>
     
       <Spin spinning={load}>
            <Table columns={columns}
            pagination={{pageSize: 5}} 
            rowSelection={{
              type: 'checkbox',
              ...rowSelection,
            }}
            dataSource={data}></Table>
        </Spin>

        <Modal title="Basic Modal" 
        forceRender
        footer={null}
        visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
            <My_modal {...my_form}></My_modal>
        </Modal>

       
    </div>
  )
}

export default OrderList